package thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * NEW->RUNNABLE->WAITING->RUNNABLE->TERMINATED
 */
public class ThreadStateNRWRTCondition {
    //锁
    private static Lock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();

    public static void main(String[] args) {
        //展示线程
        Thread showThread = new Thread(new WaitTask());
        ThreadUtils.print(showThread.getName(), showThread.getState());
        showThread.start();
        ThreadUtils.print(showThread.getName(), showThread.getState());
        //循环读取展示线程状态，直到读到展示线程状态为WAITING，才让辅助线程唤醒等待线程。
        while (true) {
            if (showThread.getState() == Thread.State.WAITING) {
                ThreadUtils.print(showThread.getName(), Thread.State.WAITING);
                break;
            }
        }

        //主线程为辅助线程，通知showThread结束等待
        lock.lock();
        try {
            System.out.println("main#signal");
            condition.signal();
        } finally {
            System.out.println("main#unlock");
            lock.unlock();
        }


        try {
            showThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //线程执行完毕打印状态。
        ThreadUtils.print(showThread.getName(), showThread.getState());
    }


    private static class WaitTask implements Runnable {
        @Override
        public void run() {
            //等待
            lock.lock();
            try {
                try {
                    System.out.println("WaitTask#await");
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } finally {
                System.out.println("WaitTask#unlock");
                lock.unlock();
            }
            ThreadUtils.print(Thread.currentThread().getName(), Thread.currentThread().getState());
        }
    }

}
